package com.ymfNetty.client;

import com.ymfNetty.message.*;
import com.ymfNetty.protocol.MessageCodecSharable;
import com.ymfNetty.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.google.common.collect.ComparisonChain.start;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
//        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        AtomicBoolean EXIT = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
//                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //判断空闲时间间隔? 读时间间隔，写时间间隔，读写时间间隔
                    // 3s 内如果没有发送给服务器 数据，会触发一个 IdleState#WRITER_IDLE事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    //处理空闲事件
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            //获取到我们要的事件类型
                            IdleStateEvent event =(IdleStateEvent) evt;
                            //触发读空闲事件
                            if(event.state()== IdleState.WRITER_IDLE){
//                                log.debug("已经3s没发数据了");
                                //发送心跳包避免被服务器断开
                                ctx.writeAndFlush(new PingMessage());
                            }

                        }
                    });
                    ch.pipeline().addLast("client handler",new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                          log.debug("msg:{}",msg);
                          if(msg instanceof LoginResponseMessage){
                              LoginResponseMessage responseMessage = (LoginResponseMessage) msg;
                              if(responseMessage.isSuccess()){
                                  LOGIN.set(true);
                                  log.info("登录成功");
                              }else{
                                  log.info("登录失败，原因：{}",responseMessage.getReason());
                              }
                              WAIT_FOR_LOGIN.countDown();//唤醒system in线程
                          }
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                           new Thread(()->{
                               Scanner scanner = new Scanner(System.in);
                               System.out.println("请输入用户名");
                               String userName = scanner.nextLine();
                               System.out.println("请输入密码");
                               String passWord = scanner.nextLine();
                               LoginRequestMessage loginRequestMessage = new LoginRequestMessage(userName, passWord);
                               ctx.writeAndFlush(loginRequestMessage);
                                System.out.println("等待后续操作...");
                               try {
                                   WAIT_FOR_LOGIN.await();//暂停线程等待
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                               // 如果登录失败
                               if (!LOGIN.get()) {
                                   ctx.channel().close();
                                   return;
                               }
                               // 构造消息对象
                               LoginRequestMessage message = new LoginRequestMessage(userName, passWord);
                               System.out.println(message);
                               while (true) {
                                   System.out.println("==================================");
                                   System.out.println("send [username] [content]");
                                   System.out.println("gsend [group name] [content]");
                                   System.out.println("gcreate [group name] [m1,m2,m3...]");
                                   System.out.println("gmembers [group name]");
                                   System.out.println("gjoin [group name]");
                                   System.out.println("gquit [group name]");
                                   System.out.println("quit");
                                   System.out.println("==================================");
                                   String command = null;
                                   try {
                                       command = scanner.nextLine();
                                   } catch (Exception e) {
                                       break;
                                   }
                                   if (EXIT.get()) {
                                       return;
                                   }
                                   String[] s = command.split(" ");
                                   switch (s[0]) {
                                       case "send":
                                           ctx.writeAndFlush(new ChatRequestMessage(userName, s[1], s[2]));
                                           break;
                                       case "gsend":
                                           ctx.writeAndFlush(new GroupChatRequestMessage(userName, s[1], s[2]));
                                           break;
                                       case "gcreate":
                                           Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                           set.add(userName); // 加入自己
                                           ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                                           break;
                                       case "gmembers":
                                           ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                           break;
                                       case "gjoin":
                                           ctx.writeAndFlush(new GroupJoinRequestMessage(userName, s[1]));
                                           break;
                                       case "gquit":
                                           ctx.writeAndFlush(new GroupQuitRequestMessage(userName, s[1]));
                                           break;
                                       case "quit":
                                           ctx.channel().close();
                                           return;
                                   }
                               }
                           },"system in").start();
                        }
                    });

                }
            });
            Channel channel = bootstrap.connect("localhost", 7077).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
